<template>
  <component ref="selectRef" :is="Selects[props.name]" v-bind="mergedProps" v-on="$attrs" />
</template>

<script setup lang="ts">
import type { SelectProps } from 'ant-design-vue'
import _ from 'lodash'
import eventEmitter from '@/lib/event-emitter'
import Selects from './components'
interface CustomProps {
  name: keyof typeof Selects
  fetchParams?: any
}

const props: CustomProps & SelectProps = defineProps<CustomProps>()
const defaultProps: Partial<CustomProps & SelectProps> = {
  showSearch: true,
  allowClear: true,
  bordered: true,
  optionFilterProp: 'label',
  dropdownMatchSelectWidth: false,
  onInputKeyDown: (e: KeyboardEvent) => {
    if (e.key === 'Enter') {
      emits('inputEnter')
    }
  }
}

// 获取Attributes
const attrs = useAttrs()

// 合并Props，确保自定义默认值优先级高
const mergedProps = computed(() => {
  return _.merge({}, defaultProps, props, attrs)
})

// 事件
const emits = defineEmits(['inputEnter'])

// 获取Ref
const selectRef = ref()
eventEmitter.on('Custom:SelectRefresh', () => {
  selectRef.value?.queryList(props.fetchParams)
})

// 监听请求参数变化
watch(
  () => props.fetchParams,
  () => {
    selectRef.value?.queryList(props.fetchParams)
  },
  {
    deep: true,
    immediate: true
  }
)
</script>
